# from datetime import datetime
from rest_framework import mixins
from rest_framework import status
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework import filters
from rest_framework import permissions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication
from django_filters.rest_framework import DjangoFilterBackend
from .filters import DeployOprationFilter
from .models import work_order
from .models import deployInfo
from .models import deploy_history
from .models import deploy_sysconf_envs
from .models import deploy_sysconf_type
from .serializers import DeployDetailSerializer
from .serializers import DeployCreateSerializer
from .serializers import ProjectNameListSerializer
from .serializers import DeployHistorySerializer
from .serializers import DeployWorkOrderDetailSerializer
from .serializers import DeployWorkOrderCreateSerializer
from .serializers import DeployTypeConfDetailSerializer
from .serializers import DeployTypeConfCreateSerializer
from .serializers import DeployEnvsConfDetailSerializer
from .serializers import DeployEvnsConfCreateSerializer
from libs.paginations import ListPagination
from .utils.app_deploy_opration import DeployCollectionLogs
from .utils.app_deploy_opration import DeployBuildApplications


class DeployTypeViewSet(viewsets.ModelViewSet):
    '''部署类型设置接口'''
    queryset = deploy_sysconf_type.objects.all()
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    permission_classes = (permissions.IsAuthenticated,)
    pagination_class = ListPagination

    def get_serializer_class(self):
        if self.action == 'create':
            return DeployTypeConfCreateSerializer
        else:
            return DeployTypeConfDetailSerializer


class DeployEnvsViewSet(viewsets.ModelViewSet):
    '''部署环境管理接口'''
    queryset = deploy_sysconf_envs.objects.all()
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    permission_classes = (permissions.IsAuthenticated,)
    pagination_class = ListPagination

    def get_serializer_class(self):
        if self.action == 'create' or self.action == 'update':
            return DeployEvnsConfCreateSerializer
        else:
            return DeployEnvsConfDetailSerializer


class DeployViewSet(viewsets.ModelViewSet):
    """
    获取应用列表
    更新应用
    删除应用
    """
    queryset = deployInfo.objects.all().order_by('id')
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    pagination_class = ListPagination
    filter_backends = (filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend)
    search_fields = ("name",)
    filter_fields = ('env', 'application_type')

    def get_serializer_class(self):
        if self.action == "create" or self.action == 'update':
            return DeployCreateSerializer
        else:
            return DeployDetailSerializer


class DeployOprationView(viewsets.GenericViewSet,
                         mixins.RetrieveModelMixin):
    '''
    项目发布
    '''

    queryset = deployInfo.objects.all()
    serializer_class = DeployDetailSerializer
    pagination_class = ListPagination
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (DjangoFilterBackend,)
    filter_class = DeployOprationFilter

    def get_object(self):
        instance = deployInfo.objects.filter(id=self.kwargs['pk']).values().first()
        app_type = instance.get('application_type')
        script_path = deploy_sysconf_type.objects.filter(name=app_type).values().first()
        # tag = datetime.now().strftime("%Y%m%d%H%M")
        # instance['image_tag'] = tag
        instance['script_path'] = script_path.get('script_path')
        res = {}
        for key, value in instance.items():
            if key not in ('id', 'create_time', 'update_time'):
                res[key] = value
        return res

    def retrieve(self, request, *args, **kwargs):
        '''
        : oprate_param: deploy  进行项目发布
        : oprate_param: logs    获取发布日志
        '''
        if len(self.request.query_params) > 0:
            oprate_param = self.request.query_params['oprate_param']
            if oprate_param in ('deploy', 'logs'):
                if oprate_param == 'deploy':
                    deploy_run = DeployBuildApplications(app_info=self.get_object())
                    deployInfo.objects.filter(name=self.get_object()['name'],
                                              env=self.get_object()['env']
                                              ).update(status='building')
                    return Response(deploy_run.run_shell_script())
                else:
                    deploy_logs = DeployCollectionLogs(app_info=self.get_object())
                    return Response(deploy_logs.read_logs())
            else:
                return Response({'msg': '错误的参数,(deploy/logs)'})
        return Response({'msg': '参数异常,(deploy/logs)'})


class ProjectNameListViewSet(viewsets.GenericViewSet,
                             mixins.ListModelMixin):
    '''项目名称和环境类型以及项目类型'''

    queryset = deployInfo.objects.all()
    serializer_class = ProjectNameListSerializer
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('env', 'application_type')


class DeployHistoryView(viewsets.GenericViewSet,
                        mixins.ListModelMixin,
                        mixins.RetrieveModelMixin):
    '''构建历史'''

    queryset = deploy_history.objects.all()
    serializer_class = DeployHistorySerializer
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('env', 'application_type', 'name')

    def list(self, request, *args, **kwargs):
        # 重写list方法，返回最后10条数据给客户端

        queryset = self.filter_queryset(self.get_queryset().order_by('-id'))[:10]
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class DeployWorkOrderViewSet(viewsets.ModelViewSet):
    '''发布工单'''

    queryset = work_order.objects.all()
    pagination_class = ListPagination
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (filters.OrderingFilter,)
    order_fields = ('id')

    def get_serializer_class(self):
        if self.action == 'list' or self.action == 'retrieve':
            return DeployWorkOrderDetailSerializer
        return DeployWorkOrderCreateSerializer

    def list(self, request, *args, **kwargs):
        username = self.request.user.username
        if username == 'admin':
            queryset = self.filter_queryset(self.get_queryset().order_by('-id'))
        else:
            queryset = self.filter_queryset(self.get_queryset().filter(submit_user=username).order_by('-id'))

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        work_order_data = self.request.data
        work_order_data['submit_user'] = self.request.user.username

        serializer = self.get_serializer(data=work_order_data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
